package com.es.demo.controller;

import com.alibaba.fastjson.JSON;
import com.es.demo.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zqf
 * @Date: 2022/10/13/22:36
 * @Description:
 */
@RestController("/doc")
@Api(tags = "添加文档")
public class AddDocController {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Value("${elasticsearch.index}")
    private String esIndex;

    @GetMapping("/add")
    @ApiOperation("创建文档数据")
    public String addDoc(@RequestParam("id") @ApiParam("es里的id，如果为空es会生成一个uuid") String id,
                         @RequestParam("name") @ApiParam("User里面name，方便创建不同的user数据") String name) throws IOException {

        // 创建一个User对象
        User user = new User();
        user.setName(name);
        user.setAge(10);
        user.setAddress("贵阳市南明区油榨街");
        user.setTimes(System.currentTimeMillis());

        // 创建请求
        IndexRequest request = new IndexRequest(esIndex);
        request.id(id);

        // 制定规则 PUT /test_index/_doc/1;设置文档ID
        request.timeout(TimeValue.timeValueMillis(1000));

        // 将我们的数据放入请求中
        request.source(JSON.toJSONString(user), XContentType.JSON);

        // 客户端发送请求，获取响应的结果
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);

        // 获取建立索引的状态信息 CREATED
        if (RestStatus.CREATED.equals(response.status())) {
            return "创建成功";
        }
        return "创建失败";
    }


    @GetMapping("/batchSave")
    @ApiOperation("批量保存文档数据")
    public String addDoc() throws IOException {

        List<User> userList = new ArrayList<>();
        BulkRequest bulkRequest = new BulkRequest();

        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setName("user batch " + i);
            user.setAge(i * 10);
            user.setAddress("贵阳市南明区油榨街");
            user.setTimes(System.currentTimeMillis());
            userList.add(user);
        }

        for (int i = 0; i < userList.size(); i++) {
            bulkRequest.add(new IndexRequest(esIndex).source(JSON.toJSONString(userList.get(i)), XContentType.JSON).id(i + "k"));
        }

        BulkResponse response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        // 获取建立索引的状态信息 CREATED
        if (!response.hasFailures()) {
            return "创建成功";
        }
        return "创建失败";
    }
}